package com.cyrilmottier.android.gdcatalog;

import greendroid.app.GDActivity;
import greendroid.widget.ActionBarItem;
import greendroid.widget.ActionBarItem.Type;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cyrilmottier.android.gdcatalog.util.Constants;
import com.google.android.maps.GeoPoint;

public class ExplorationActivity extends GDActivity {

	private ImageView mPhotoImageView;
	private ImageView mSignImageView;
	private Bitmap myBitmap;

	private String photoDir, signDir;
	
	private Location location;
	private LocationManager locationManager;

	@Override
	public void setTitle(int titleId) {
		super.setTitle(R.string.takandan);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setActionBarContentView(R.layout.exploration);

		addActionBarItem(Type.TakePhoto, R.id.action_bar_export);
		addActionBarItem(Type.Edit, 1);
		addActionBarItem(Type.Locate, R.id.action_bar_locate);
		addActionBarItem(Type.Mail, R.id.action_bar_view_info);
		mPhotoImageView = (ImageView) this.findViewById(R.id.imageView);
		mPhotoImageView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent getImageByCamera = new Intent(
						"android.media.action.IMAGE_CAPTURE");
				startActivityForResult(getImageByCamera, R.id.action_bar_export);
			}
		});
		mSignImageView = (ImageView) this.findViewById(R.id.simageView);
		mSignImageView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(ExplorationActivity.this,
						TouchPaint.class);
				startActivityForResult(intent, R.id.action_bar_locate);
			}
		});

		// ----------
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		location = locationManager
				.getLastKnownLocation(LocationManager.GPS_PROVIDER);

		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
				2000, 0, locationListener);
	}

	private String getCurrentPoint() {
		GeoPoint point = null;
		if (location == null) { // 没有最后位置，更新gps,获取当前位置
			point = new GeoPoint(37774900, -122419400);
		} else { // 当前反馈的GPS位置
			Double lat = location.getLatitude() * 1E6;
			Double lng = location.getLongitude() * 1E6;
			point = new GeoPoint(lat.intValue(), lng.intValue());
		}
		return point.toString();

	}

	private final LocationListener locationListener = new LocationListener() {
		public void onLocationChanged(Location location) {
			updateWithNewLocation(location);
		}

		public void onProviderDisabled(String provider) {
			updateWithNewLocation(null);
		}

		public void onProviderEnabled(String provider) {
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	};

	private void updateWithNewLocation(Location location) {
		String latLongString;
		TextView myLocationText;
		myLocationText = (TextView) findViewById(R.id.textView423);
		if (location != null) {
			double lat = location.getLatitude();
			double lng = location.getLongitude();
			latLongString = "纬度:" + lat + "\n经度:" + lng;
		} else {
			latLongString = "无法获取地理信息";
		}
		myLocationText.setText("您当前的位置是:\n" + latLongString);
	}

	@Override
	public boolean onHandleActionBarItemClick(ActionBarItem item, int position) {
		switch (item.getItemId()) {
		case R.id.action_bar_locate:
			Intent mapIntent = new Intent(ExplorationActivity.this,
					MapPinMapActivity.class);
			startActivity(mapIntent);
			break;
		case 1:
			Toast.makeText(
					this,
					String.format("正在上传%s探勘单和%s签名, \n当前GPS位置是%s", new Object[] {
							photoDir, signDir, getCurrentPoint() }),
					Toast.LENGTH_LONG).show();
			break;
		default:
			return super.onHandleActionBarItemClick(item, position);
		}

		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		try {
			if (requestCode == R.id.action_bar_export) {
				super.onActivityResult(requestCode, resultCode, data);
				System.out
						.println("=====================================================");
				Bundle extras = data.getExtras();
				myBitmap = (Bitmap) extras.get("data");
				mPhotoImageView.setImageBitmap(myBitmap);
				// 保存到SD卡上
				System.out.println("SD_CARD_TEMP_DIR : "
						+ Constants.SD_CARD_TEMP_DIR);
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

				byte[] photoBytes = baos.toByteArray();

				File aFile = new File(
						getGenerationFilename(Constants.SD_CARD_TEMP_DIR));

				if (aFile.exists()) {
					aFile.delete();
				}
				aFile.createNewFile(); // need add permission to manifest
				FileOutputStream fos = new FileOutputStream(aFile);
				fos.write(photoBytes);
				fos.close();
				photoDir = aFile.getAbsolutePath();
			} else if (requestCode == R.id.action_bar_locate) {
				Bundle extras = data.getExtras();
				String signature = signDir = (String) extras.get("signature");
				FileInputStream fis = new FileInputStream(signature);
				mSignImageView.setImageBitmap(BitmapFactory.decodeStream(fis));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String getGenerationFilename(String fname) {
		StringBuffer result = new StringBuffer();

		SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");
		String dateSfx = "_" + df.format(new Date());

		int idx = fname.lastIndexOf('.');
		if (idx != -1) {
			result.append(fname.substring(0, idx));
			result.append(dateSfx);
			result.append(fname.substring(idx));
		} else {
			result.append(fname);
			result.append(dateSfx);
		}

		return result.toString();
	}

}